import requests
from typing import Optional, Dict, Any, Union
import os

def upload_attachment_to_external_system(
    file_path: str,
    external_api_url: str,
    headers: Optional[Dict[str, str]] = None,
    additional_data: Optional[Dict[str, Any]] = None,
    timeout: int = 300
) -> Dict[str, Any]:
    """
    上传附件到外部系统

    Args:
        file_path (str): 本地文件路径
        external_api_url (str): 外部系统的上传API地址
        headers (dict, optional): 请求头信息，如认证信息等
        additional_data (dict, optional): 需要一同发送的额外数据
        timeout (int): 请求超时时间（秒）

    Returns:
        dict: 外部系统的响应结果

    Raises:
        FileNotFoundError: 当指定的文件不存在时
        requests.RequestException: 当HTTP请求失败时
    """
    # 检查文件是否存在
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"文件 {file_path} 不存在")

    # 准备请求数据
    files = {}
    data = additional_data or {}

    try:
        # 打开文件准备上传
        with open(file_path, 'rb') as file:
            files['file'] = (os.path.basename(file_path), file)

            # 发送POST请求到外部系统
            response = requests.post(
                external_api_url,
                files=files,
                data=data,
                headers=headers,
                timeout=timeout
            )

            # 检查响应状态
            response.raise_for_status()

            # 尝试解析JSON响应
            try:
                return {
                    'success': True,
                    'status_code': response.status_code,
                    'data': response.json()
                }
            except ValueError:
                return {
                    'success': True,
                    'status_code': response.status_code,
                    'data': response.text
                }

    except requests.RequestException as e:
        return {
            'success': False,
            'error': str(e),
            'error_type': 'request_error'
        }
    except Exception as e:
        return {
            'success': False,
            'error': str(e),
            'error_type': 'unknown_error'
        }

def upload_attachment_with_auth(
    file_path: str,
    external_api_url: str,
    auth_token: str,
    auth_type: str = "Bearer",
    additional_data: Optional[Dict[str, Any]] = None,
    timeout: int = 30
) -> Dict[str, Any]:
    """
    使用认证信息上传附件到外部系统

    Args:
        file_path (str): 本地文件路径
        external_api_url (str): 外部系统的上传API地址
        auth_token (str): 认证令牌
        auth_type (str): 认证类型，默认为"Bearer"
        additional_data (dict, optional): 需要一同发送的额外数据
        timeout (int): 请求超时时间（秒）

    Returns:
        dict: 外部系统的响应结果
    """
    headers = {
        "Authorization": f"{auth_type} {auth_token}"
    }

    return upload_attachment_to_external_system(
        file_path=file_path,
        external_api_url=external_api_url,
        headers=headers,
        additional_data=additional_data,
        timeout=timeout
    )

# # 基础用法
# result = upload_attachment_to_external_system(
#     file_path="/path/to/document.pdf",
#     external_api_url="https://api.external-system.com/upload"
# )
#
# # 带认证的用法
# result = upload_attachment_with_auth(
#     file_path="/path/to/document.pdf",
#     external_api_url="https://api.external-system.com/upload",
#     auth_token="your-access-token"
# )
#
# # 带额外数据的用法
# result = upload_attachment_to_external_system(
#     file_path="D:\《人工智能知识工程指南（1.0）》.pdf",
#     external_api_url="https://api.external-system.com/upload",
#     headers={"Custom-Header": "value"},
#     additional_data={"category": "document", "description": "重要文件"}
# )


if __name__ == "__main__":
    path_1 = "D:\\《人工智能知识工程指南（1.0）》.pdf"
    path_2 = "D:\\VE_LOC_ROOM_15_20240923-008.CSV"
    path_3 = "D:\\VE_LOC_ROOM_15_20240923-009.CSV"

    result = upload_attachment_to_external_system(
        file_path=path_3,
        external_api_url="http://192.168.0.226:10014/nop/upload",
        headers={"pass-over": "let it go","Encode-Type":"no-encode"},
        additional_data={"pathParam": "tmpUpload/202507/2410/2/849f3019-d135-0050-9d5e-876235402f5a/13", "typeParam": "html",
                         "transformParam": 0,"recordToDbParam":True,"basePathParam":"File_Path",
                         "userName":"admin","userId":"1","nopFile":True,"token":"9647E1A3E294A81AE1BC02106CD25F12"}
    )
    print(f"{result}")

    result = upload_attachment_to_external_system(
        file_path=path_1,
        external_api_url="http://192.168.0.226:10011/mtex/file/nop/upload",
        headers={"pass-over": "let it go", "Encode-Type": "no-encode"},
        additional_data={"pathParam": "tmpUpload/202507/2410/2/849f3019-d135-0050-9d5e-876235402f5a/13",
                         "typeParam": "html",
                         "transformParam": 0, "recordToDbParam": True, "basePathParam": "File_Path",
                         "userName": "admin", "userId": "1", "nopFile": True,
                         "token": "9647E1A3E294A81AE1BC02106CD25F12"}
    )
    print(f"{result}")

    result = upload_attachment_to_external_system(
        file_path=path_1,
        external_api_url="http://192.168.0.226:10011/mtex/file/upload/toNop",
        headers={"pass-over": "let it go", "Encode-Type": "no-encode"},
        additional_data={"pathParam": "tmpUpload/202507/2410/2/849f3019-d135-0050-9d5e-876235402f5a/13",
                         "typeParam": "html",
                         "transformParam": 0, "recordToDbParam": True, "basePathParam": "File_Path",
                         "userName": "admin", "userId": "1", "nopFile": True,
                         "token": "9647E1A3E294A81AE1BC02106CD25F12"}
    )
    print(f"{result}")
